import axios from 'axios'
import { nativeHandler } from 'qmp-native'
import { Toast } from 'qmp-component'
const { programmeFlag } = require('@/config/settings') // 当前项目名称
// const BASE = require('@/config/index')
const service = axios.create({
  //   baseURL: process.env.QMP_EVN === 'development' ? '' : BASE.baseUrl,
  timeout: 10000
})

service.interceptors.request.use(
  async (config: any) => {
    // 本地开发时匹配本地代理的接口基础地址
    if (process.env.QMP_EVN === 'development') {
      config.headers['Authorization'] = `Bearer 35e46d72-5b38-4d4a-9e9b-2e45bbf659f4`
      config.baseURL = `/${config.projectName || programmeFlag}`
      return config
    }

    const { token } = await nativeHandler()
    config.headers['Authorization'] = `${token}`
    // 非本地开发时，通过底座方法获取当前对应应用、对应环境的接口基础地址(实现一个包可用于移动门户或UU协同的正式和测试环境)
    const { data } = await nativeHandler('getServerUrl', '')
    config.baseURL = data + (config.projectName || programmeFlag)
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    return Promise.resolve(response.data)
  },
  (error) => {
    const { name, message } = JSON.parse(JSON.stringify(error))
    if (name === 'Error' && message.indexOf('status code 401') !== -1) {
      Toast.fail('登录已失效')
    } else {
      Toast.fail('后台服务异常')
    }
    return Promise.reject(error)
  }
)

export default service
